define(['angularAMD'], function (angularAMD) {
    angularAMD.service('G0103Service', ['$rootScope', '$filter', '$translate', 'config', 'MMWService', '$mdDialog','$timeout',
        function ($rootScope, $filter, $translate, config, $MMWService, $mdDialog, $timeout) {
            /**
             *  subOpInfo: 子作業首頁單頭
             *  subOpItem: 子作業首頁單身項目
             *  callback: function
             */
            this.init = function(options){
                //option = {subOpInfo};
                var employee_work_reason = config.cache.sys_parameter.EmployeeWorkReason;

                 // 是否需要人員上/下工原因，1. 上工 2. 下工 3. 皆需要
                function isNeedWorkReason(work_mode){
                    var result = false;

                    if(employee_work_reason){
                        if(work_mode == 'U' && employee_work_reason == '1') {
                            result = true;
                        } else if ((work_mode == 'D' || work_mode == 'AD') && employee_work_reason == '2') {
                            result = true;
                        } else if(employee_work_reason == '3'){
                            result = true;
                        }
                    }

                    return result;
                }

                function beforeEmpWorkSet(dialog, work_mode, callback){
                    if(!dialog.tmpOnWorkInfo.reason_no && isNeedWorkReason(work_mode)){
                        loadEmpWorkReason(dialog, work_mode, function(selectItem){
                            dialog.tmpOnWorkInfo.reason_no = selectItem.page_no;
                            dialog.tmpOnWorkInfo.reason_name = selectItem.page_name;
                            if (callback)
                                callback();
                        });
                    } else {
                        if (callback)
                            callback();
                    }
                }

                function SMES_EmployeeWrokSet_Imp(dialog, work_mode, callback){
                    beforeEmpWorkSet(dialog, work_mode, function(){
                        var content = {
                            platform_type: '1', //作業平台:0: 預設(生產線、作業人員、作業區、工位機) 1: 子作業作業平台
                            employeewrokset: []
                        };
                        if(work_mode == 'U' || work_mode == 'D'){ // 上/下工
                            content.employeewrokset = [dialog.tmpOnWorkInfo];
                        } else if(work_mode == 'AD'){ // 全數下工
                            var employeewrokset = [];
                            dialog.subOpItem.employee_work_detail.forEach(function(employee){
                                employeewrokset.push({
                                    machine_no : dialog.plot_no, //子作業以生產批編號作為上工依據
                                    employee_no : employee.employee_no,
                                    work_mode : 'D',
                                    work_datetime : moment().format('YYYY/MM/DD HH:mm:ss'),
                                    reason_no: dialog.tmpOnWorkInfo.reason_no || '',
                                    op_no: options.op_no,
                                    sub_op_no: options.subOpItem.sub_op_no,
                                });
                            });

                            content.employeewrokset = employeewrokset;
                        }

                        SMES_EmployeeWrokSet(content, function(){
                            $rootScope.showToast($filter('translate')('G0103.msg.success_'+ work_mode));
                            dialog.tmpOnWorkInfo = {};
                            dialog.tmpEmp_no = '';
                            dialog.ic_card = '';
                            if (callback)
                                callback();
                        });
                    });
                }

                // 人員原因基本資料取得
                function loadEmpWorkReason(dialog, work_mode, callback){
                    var query_condition_info = [{column_name:'ISSUESTATE', query_mode:'0', value:'2', merge_condition_model:'AND'}];

                    if(work_mode == 'D' || work_mode == 'AD'){ // 下工
                        query_condition_info.push({column_name:'REASONTYPE', query_mode:'0', value:'1', merge_condition_model:'AND' });
                    } else if(work_mode == 'U'){ //上工
                        query_condition_info.push({column_name:'REASONTYPE', query_mode:'0', value:'0', merge_condition_model:'AND' });
                    }

                    $MMWService.pageNumberInfoGet({
                        page_mode : '35',
                        query_condition_info: query_condition_info
                    }, function(items){
                        if(items && items.length > 0){
                            $rootScope.showSelect({
                                label : function(item){
                                    return item.page_name + '(' + item.page_no + ')';
                                },
                                title: $filter('translate')('G0103.plz_select_reason_' + work_mode),
                                code : 'page_no',
                                selectCode : dialog.tmpOnWorkInfo.reason_no || '',
                                list : items,
                                confirm : function(selectItem, radio_dialog){
                                    radio_dialog.hide();
                                    if (callback)
                                        callback(selectItem);
                                }
                            });
                        } else {
                            $rootScope.showAlert($filter('translate')('G0103.msg.reason_empty_'+work_mode));
                        }
                    });
                }

                function SMES_UserInformationGet(dialog, callback){
                    var content = {
                        machine_no : dialog.plot_no, //子作業以生產批編號作為上工依據
                        employee_no : dialog.tmpEmp_no,
                        report_datetime : new Date(),
                        return_type : '10'
                    };

                    $MMWService.sendToServer({
                        uri: 'ServicesSTD.Module_SYS.user_information_get',
                        content : content,
                        success : function(data){
                            if(callback)
                                callback(data);
                        },
                        error : function(data){
                            $rootScope.showAlert(data.Message, function(){
                                dialog.tmpOnWorkInfo = {};
                                dialog.tmpEmp_no = '';
                                dialog.ic_card = '';
                                dialog.mode = undefined;
                                dialog.beforeShown();
                            });
                        }
                    });
                }

                function SMES_EmployeeWrokSet(content, callback){
                    $MMWService.sendToServer({
                        uri: 'ServicesSTD.Module_SYS.employee_wrok_set_process',
                        content : content,
                        success : function(data){
                            if(callback)
                                callback();
                        }
                    });
                }


                $mdDialog.dialog(
                    'module/moduleG/program/G01/G0103/G0103.html',
                    function(dialog){
                        return {
                            css_url:'module/moduleG/program/G01/G0103/G0103.css',
                            tmpEmp_no : '',
                            tmpOnWorkInfo : {},
                            pdline_no: options.pdline_no,
                            op_no: options.op_no,
                            plot_no: options.plot_no,
                            cur_qty: options.cur_qty,
                            subOpItem: options.subOpItem,
                            ic_card: '',  //IC卡
                            ICCardScanner: function () {//20200723 add by linzh for M#71988
                                $rootScope.OpenScanner({
                                    after: function (result) {
                                        $timeout(function () {
                                            dialog.ic_card = result.text;
                                            dialog.searchICCard();
                                        });
                                    },
                                    exception: function () {
                                        //目前裝置無法使用相機
                                        $rootScope.showAlert($filter('translate')('B0214.showAlert.column3'));
                                    },
                                    orientation: 'landscape'
                                });
                            },
                            searchICCard: function (event) {//20200710 add by linzh for M#71988
                                if (!event || event.keyCode == 13) {
                                    if (dialog.ic_card != '') {
                                        var content = {
                                            IcNo: dialog.ic_card
                                        }
                                        $MMWService.sendToServer({
                                            uri: 'ServicesSTD.Module_SYS.ic_card_info_get',
                                            content: content,
                                            success: function (data) {
                                                if (data.UserNo != null && data.PassWord != null) {
                                                    dialog.tmpEmp_no = data.UserNo;
                                                    // 20220316 modify by chenshibo for#108030：子作业站上工，刷卡上工一次后，光标就自动跳转到其它输入框
                                                    dialog.searchEmp(undefined,"1");//调用员工信息查询方法
                                                }
                                                else {
                                                    $rootScope.showAlert($filter('translate')('Login.error.ic_card_error'));
                                                    dialog.ic_card = '';
                                                    document.getElementById('ic_card').focus();
                                                }
                                            },
                                            error: function (data) {
                                                $rootScope.showAlert(data.Message);
                                                dialog.ic_card = '';
                                                document.getElementById('ic_card').focus();
                                            }
                                        });
                                    } else {
                                        $rootScope.showAlert($filter('translate')('G0103.msg.ic_card_empty'));
                                        dialog.ic_card = '';
                                        document.getElementById('ic_card').focus();
                                    }
                                }
                            },
                            beforeShown: function(){
                                var target = document.getElementById('tmpEmp_no');
                                if(target)
                                    target.focus();
                            },
                            // 20220316 modify by chenshibo for#108030：子作业站上工，刷卡上工一次后，光标就自动跳转到其它输入框
                            targeticcard: function () {
                                var target = document.getElementById('ic_card');
                                if (target)
                                    target.focus();
                            },
                            searchEmp: function (event, isICCard){
                                if(!event || event.keyCode==13){
                                    if(dialog.tmpEmp_no!=''){
                                        dialog.tmpEmp_no = dialog.tmpEmp_no.toUpperCase();
                                        SMES_UserInformationGet(dialog, function(data){
                                            dialog.tmpOnWorkInfo = data;
                                            dialog.tmpOnWorkInfo.machine_no = options.plot_no; //子作業以生產批編號作為上工依據
                                            dialog.tmpOnWorkInfo.work_datetime = new Date();
                                            dialog.tmpOnWorkInfo.op_no = options.op_no;
                                            dialog.tmpOnWorkInfo.sub_op_no = options.subOpItem.sub_op_no;
                                            var temp = $filter('filter')(dialog.subOpItem.employee_work_detail,{employee_no:dialog.tmpOnWorkInfo.employee_no}, true);
                                            if(temp && temp.length> 0){
                                                dialog.tmpOnWorkInfo.work_mode = 'D';
                                                if(config.setting.autoWorkset)
                                                    dialog.employeeWrokSet(isICCard);
                                            } else {
                                                dialog.tmpOnWorkInfo.work_mode = 'U';
                                                if(config.setting.autoWorkset)
                                                    dialog.employeeWrokSet(isICCard);
                                            }
                                        });
                                    }else{
                                        $rootScope.showAlert($filter('translate')('G0103.msg.emp_no_empty'), function(){
                                            dialog.tmpOnWorkInfo = {};
                                            dialog.mode = undefined;
                                            dialog.beforeShown();
                                        });
                                    }
                                }
                            },
                            selectEmployee:function(item){
                                dialog.tmpEmp_no = item.employee_no;
                                 // 20220316 modify by chenshibo for#108030：子作业站上工，刷卡上工一次后，光标就自动跳转到其它输入框
                                dialog.searchEmp(undefined,"0");
                            },
                            isNeedWorkReason: function(){
                                return isNeedWorkReason(dialog.tmpOnWorkInfo.work_mode);
                            },
                            isDataPrepared: function(){
                                return (dialog.tmpOnWorkInfo != null) && !angular.equals({}, dialog.tmpOnWorkInfo);
                            },
                            loadEmpWorkReason: function(){
                                loadEmpWorkReason(dialog, dialog.tmpOnWorkInfo.work_mode, function(selectItem){
                                    dialog.tmpOnWorkInfo.reason_no = selectItem.page_no;
                                    dialog.tmpOnWorkInfo.reason_name = selectItem.page_name;
                                });
                            },
                            back: function () {
                                dialog.hide();
                                if(options.close)
                                    options.close();
                            },
                            employeeWrokSet: function (isICCard) {
                                var work_mode = dialog.tmpOnWorkInfo.work_mode;
                                if(!config.cache.permissions){
                                    //全權限
                                    SMES_EmployeeWrokSet_Imp(dialog, work_mode, function(){
                                        if(options.callback)
                                            if (options.callback)
                                                if (isICCard == "1") {
                                                    options.callback(dialog.targeticcard, dialog);
                                                }
                                                else {
                                                    options.callback(dialog.beforeShown, dialog);
                                                }
                                    });
                                } else{
                                    if(config.cache.permissions.indexOf(work_mode=='U'?'B0202':'B0203')!=-1){
                                        SMES_EmployeeWrokSet_Imp(dialog, work_mode, function(){
                                            if(options.callback)
                                                if (isICCard == "1") {
                                                    options.callback(dialog.targeticcard, dialog);
                                                }
                                                else {
                                                    options.callback(dialog.beforeShown, dialog);
                                                }
                                        });
                                    } else {
                                        $rootScope.showAlert($filter('translate')('common.msg.no_permissions'));
                                    }
                                }
                            },
                            employeeWrokSetAll: function(){
                                if(!config.cache.permissions){
                                    SMES_EmployeeWrokSet_Imp(dialog, 'AD', function(){
                                        if(options.callback)
                                            options.callback(dialog.beforeShown, dialog);
                                    });
                                } else{
                                    if(config.cache.permissions.indexOf('B0203')!=-1){
                                        SMES_EmployeeWrokSet_Imp(dialog, 'AD', function(){
                                            if(options.callback)
                                                options.callback(dialog.beforeShown, dialog);
                                        });
                                    } else {
                                        $rootScope.showAlert($filter('translate')('common.msg.no_permissions'));
                                    }
                                }
                            },
                            reportProcess: function(){
                                $mdDialog.serviceDialog('G0104Service',{area_no: options.pdline_no}, {
                                    plot_no: options.plot_no,
                                    op_no: options.op_no,
                                    sub_op_no: options.subOpItem.sub_op_no,
                                    sub_op_name: options.subOpItem.sub_op_name,
                                    record_eqp: options.subOpItem.record_eqp
                                },
                                'G0103',
                                function(){
                                    if(options.callback)
                                        options.callback(dialog.beforeShown, dialog);
                                });
                            },
                        };
                    }
                );
            };
        }]);
});
